package com.libs.agricultural;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;

import com.libs.agricultural.R;
import com.libs.agricultural.Login.myThread;
import com.libs.model.log;
import com.libs.model.parameter;
import com.libs.model.user;
import common.HttpHelper;
import common.JSONHelper;
import common.Urls;
import common.Userinfo;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint.Align;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AddressFragment extends Fragment implements OnClickListener
{
	private Context context;
	private TextView dateText;
	private Spinner data_type;
	
	Calendar c = Calendar.getInstance();
	private int year = c.get(Calendar.YEAR);
	private int monthOfYear = c.get(Calendar.MONTH);
	private int dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
	private String timeNow= year + "-"+ (monthOfYear + 1) + "-" + dayOfMonth;
	private String dataType="温度";
	
	private HttpHelper hlper;
	private View view;
	
	class myThreadParam implements Runnable {   
		public void run() {  
	    	hlper=new HttpHelper();
	    	List<NameValuePair> parn=new ArrayList<NameValuePair>();
	    	parn.add(new BasicNameValuePair("type", "AllInfo"));
	    	parn.add(new BasicNameValuePair("id", Userinfo.num+""));
	    	parn.add(new BasicNameValuePair("time",timeNow));
	    	JSONArray json=hlper.HttpList(Urls.ParameterUrl, parn);
	    	if(json!=null){
	    		parameter[] uu=null;
	    		try {
					uu=JSONHelper.parseArray(json, parameter.class);
					List<parameter> list=new ArrayList<parameter>();
					for(int i=0;i<uu.length;i++){
						list.add(uu[i]);
					}
					Message message = new Message();   
			        message.what = 1;
			        message.obj=list;
			        myHandlerparam.sendMessage(message);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	    	}
	    	if(json==null){
	    		Message message = new Message();   
		        message.what = 1;
		        message.obj=null;
		        myHandlerparam.sendMessage(message);
	    	}
	    }   
	}
	private Handler myHandlerparam = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {   
            case 1:   
            	List<parameter> uuu=(List<parameter>) msg.obj;
            	chartView(context,view,uuu);
                break; 
       }   
		};
   };
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState)
	{
		view = inflater.inflate(R.layout.tabdata, container, false);
		context=container.getContext();
		
		dateText=(TextView) view.findViewById(R.id.date);
		dateText.setOnClickListener(this);
		dateText.setText(timeNow);
		data_type=(Spinner) view.findViewById(R.id.data_type);
		data_type.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				String[] languages = getResources().getStringArray(R.array.type);
				dataType=languages[arg2];
				new Thread(new myThreadParam()).start();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		//new Thread(new myThreadParam()).start();
		return view;
	}
	private void chartView(Context context2, View view,List<parameter> parameter) {
		LinearLayout layout=(LinearLayout)view.findViewById(R.id.chart);
		if(parameter!=null){
			View chat= lineView(context2,parameter);
			layout.removeAllViews();
			layout.addView(chat);
		}
		else{
			layout.removeAllViews();
			TextView tt=new TextView(context2);
			tt.setText("没有数据！");
			tt.setTextSize(22);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
            tt.setLayoutParams(lp);
            tt.setGravity(Gravity.CENTER);
            layout.addView(tt);
            
		}
		
		
	}
	public View lineView(Context context,List<parameter> parameter){  

        XYMultipleSeriesRenderer mRenderer = new XYMultipleSeriesRenderer();  
        mRenderer.setZoomEnabled(false,false);
        mRenderer.setPanEnabled(false);
        mRenderer.setShowLegend(false);
        mRenderer.setMarginsColor(Color.WHITE);
        mRenderer.setXLabelsAlign(Align.RIGHT);//刻度线与刻度标注之间的相对位置关系  
        mRenderer.setYLabelsAlign(Align.LEFT);//刻度线与刻度标注之间的相对位置关系  
        
        //设置图表的X轴的当前方向  
        mRenderer.setOrientation(XYMultipleSeriesRenderer.Orientation.HORIZONTAL);  
//        mRenderer.setXTitle("时间");//设置为X轴的标题  
//        mRenderer.setYTitle("价格");//设置y轴的标题  
        mRenderer.setAxisTitleTextSize(40);//设置轴标题文本大小  
//        mRenderer.setChartTitle("实时环境参数曲线显示");//设置图表标题  
//        mRenderer.setChartTitleTextSize(60);//设置图表标题文字的大小  
        mRenderer.setLabelsTextSize(30);//设置标签的文字大小  
        mRenderer.setLegendTextSize(20);//设置图例文本大小  
        mRenderer.setPointSize(10f);//设置点的大小  
//        mRenderer.setXLabels(12);  
//        mRenderer.setYLabels(10);    
        mRenderer.setShowGrid(true);//显示网格  
        //将x标签栏目显示如：1,2,3,4替换为显示1月，2月，3月，4月  
//        mRenderer.addXTextLabel(1, "1点");  
//        mRenderer.addXTextLabel(2, "2点");  
//        mRenderer.addXTextLabel(3, "3点");  
//        mRenderer.addXTextLabel(4, "4点");  
        mRenderer.setXLabels(0);//设置只显示如1月，2月等替换后的东西，不显示1,2,3等  
        mRenderer.setMargins(new int[] { 50, 50, 50, 50 });//设置视图位置  
        XYSeriesRenderer r = new XYSeriesRenderer();//(类似于一条线对象)  
        r.setColor(Color.GREEN);//设置颜色  
        r.setPointStyle(PointStyle.CIRCLE);//设置点的样式  
        r.setFillPoints(true);//填充点（显示的点是空心还是实心）  
        r.setDisplayChartValues(true);//将点的值显示出来  
        r.setChartValuesSpacing(20);//显示的点的值与图的距离  
        r.setChartValuesTextSize(25);//点的值的文字大小  
        r.setLineWidth(3);//设置线宽  
        mRenderer.addSeriesRenderer(r);  
      //同样是需要数据dataset和视图渲染器renderer  
        XYMultipleSeriesDataset mDataset = new XYMultipleSeriesDataset();  
        XYSeries  series = new XYSeries("");
        double min=Double.valueOf(parameter.get(0).getHours());;
        double max=Double.valueOf(parameter.get(0).getHours());;
        for(int i=0;i<parameter.size();i++){
        	double hour=Double.valueOf(parameter.get(i).getHours());
        	//android.util.Log.i("lbs", hour+"");
        	mRenderer.addXTextLabel(i, (int)hour+"时");
        	if(dataType.equals("温度")){
        		mRenderer.setYTitle("温度/℃");
        		double yv=Double.valueOf(parameter.get(i).getTemperature());
        		if(yv>max){ max = yv;}
        		if(yv<min){ min = yv;}   
        		series.add(i, yv);
        	}
        	if(dataType.equals("湿度")){
        		mRenderer.setYTitle("湿度/%RH");
        		double yv=Double.valueOf(parameter.get(i).getHumidity());
        		if(yv>max){ max = yv;}
        		if(yv<min){ min = yv;}
        		series.add(i, yv);
        	}
        	if(dataType.equals("光照")){
        		mRenderer.setYTitle("光照/LUX");
        		double yv=Double.valueOf(parameter.get(i).getIllumination());
        		if(yv>max){ max = yv;}
        		if(yv<min){ min = yv;}
        		series.add(i, yv);
        	}
        	if(dataType.equals("土壤湿度")){
        		mRenderer.setYTitle("土壤湿度/%vol");
        		double yv=Double.valueOf(parameter.get(i).getMoisture());
        		if(yv>max){ max = yv;}
        		if(yv<min){ min = yv;}
        		series.add(i, yv);
        	}
        	if(dataType.equals("CO₂")){
        		mRenderer.setYTitle("CO₂/ppm");
        		double yv=Double.valueOf(parameter.get(i).getCardioxide());
        		if(yv>max){ max = yv;}
        		if(yv<min){ min = yv;}
        		series.add(i, yv);
        	}
        	if(dataType.equals("烟雾")){
        		mRenderer.setYTitle("烟雾/KWh");
        		double yv=Double.valueOf(parameter.get(i).getSmoke());
        		if(yv>max){ max = yv;}
        		if(yv<min){ min = yv;}
        		series.add(i, yv);
        	}
        	if(dataType.equals("粉尘")){
        		mRenderer.setYTitle("粉尘/V");
        		double yv=Double.valueOf(parameter.get(i).getDust());
        		if(yv>max){ max = yv;}
        		if(yv<min){ min = yv;}
        		series.add(i, yv);
        	}
        	if(dataType.equals("可燃气体")){
        		mRenderer.setYTitle("可燃气体/%");
        		double yv=Double.valueOf(parameter.get(i).getGas());
        		if(yv>max){ max = yv;}
        		if(yv<min){ min = yv;}
        		series.add(i, yv);
        	}
        }
        mRenderer.setXAxisMin(-1);
        mRenderer.setXAxisMax(parameter.size());
        mRenderer.setYAxisMin(min-20);
        mRenderer.setYAxisMax(max+20);
        mDataset.addSeries(series);
          
        GraphicalView  view = ChartFactory.getLineChartView(context, mDataset, mRenderer);  
        return view;
	}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.date:
			showDialog();
			break;
		}
	}
	private void showDialog() {	
		DatePickerDialog date = new DatePickerDialog(context,
				new OnDateSetListener() {
					@Override
					public void onDateSet(DatePicker view, int year,
							int monthOfYear, int dayOfMonth) {
						dateText.setText( year + "-"
								+ (monthOfYear + 1) + "-" + dayOfMonth);
						timeNow=dateText.getText().toString();
						new Thread(new myThreadParam()).start();
					}
				}, year, monthOfYear, dayOfMonth);
		date.show();
	}
}


